package hang.xipujewelWeb.service.account;

import hang.xipujewelWeb.entity.app.Order;
import hang.xipujewelWeb.repository.jpa.OrderDao;
import hang.xipujewelWeb.service.common.JpaManager;

import java.util.List;
import java.util.Map;

import net.esoar.modules.persistence.FilterUtil;

import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class OrderManager extends JpaManager<Order, OrderDao> {

	private static Logger logger = LoggerFactory.getLogger(OrderManager.class);

	@Autowired
	private OrderDao orderDao;

	public List<Order> findAllByUser(Long userId) {
		return orderDao.findAllByUser(userId);
	}

	/**
	 *  先删除中间表，再删除订单记录
	 * @param id
	 */
	public void deleteOrder(Long id) {
		Session session = (Session) entityManager.getDelegate();
		String queryString1 = "delete from order_jewel where order_id=" + id;
		String queryString2 = "delete from order_ring where order_id=" + id;
		session.createSQLQuery(queryString1).executeUpdate();
		session.createSQLQuery(queryString2).executeUpdate();
		orderDao.delete(id);
	}

	public List<Order> search(Map<String, Object> searchParams) {
		Specification<Order> spec = FilterUtil.builderSpecification(searchParams, Order.class);
		return orderDao.findAll(spec);
	}

	public void clearCache() {
		entityManager.clear();
	}

	/**
	 *  先删除中间表，再删除订单记录
	 * @param id
	 */
	public void deleteOrders(List<Long> ids) {
		for (Long id : ids) {
			deleteOrder(id);
		}
	}

	@Override
	protected OrderDao getDao() {
		return orderDao;
	}

}
